package com.jy.oms.framework.asyn.task.executor.filter;

import com.jy.oms.framework.asyn.task.constants.TaskQueueTypeEnum;
import com.jy.oms.framework.asyn.task.core.ExecutorConfig;
import com.jy.oms.framework.asyn.task.core.ExecutorContext;
import com.jy.oms.framework.asyn.task.core.WorkerServerThreadManager;
import com.jy.oms.framework.asyn.task.executor.ITaskControllerFilter;
import com.jy.oms.framework.asyn.task.handler.ITaskHandlerProcessor;
import com.jy.oms.framework.asyn.task.model.TaskGroup;
import org.springframework.stereotype.Service;

/**
 * 判断当前应用服务器是否可运行任务
 *
 * @author liuquan
 */
@Service
public class WorkerServerControllerFilter implements ITaskControllerFilter, ITaskHandlerProcessor {

    private volatile boolean canConsumeTask = false;

    @Override
    public boolean checkTaskGroupAbleRun(TaskGroup taskGroup) {
        if (canConsumeTask) {
            return true;
        }

        ExecutorConfig executorConfig = ExecutorContext.getExecutorConfig();
        //redis/mem任务队列可多节点执行，可充分利用机器资源
        if (TaskQueueTypeEnum.REDIS == taskGroup.getTaskQueueType()
                || TaskQueueTypeEnum.MEM == taskGroup.getTaskQueueType()) {
            if (executorConfig.isEnableRedisTaskRunInClusterMode()) {
                return true;
            }
        }

        //DB任务队列只能单节点执行
        return WorkerServerThreadManager.getInstance().isWorkerServer();
    }

    @Override
    public void processAfterTaskHandlerInitialization() {
        ExecutorConfig executorConfig = ExecutorContext.getExecutorConfig();
        //本地环境 或 多节点环境下， 无需启动心跳线程
        if (ExecutorContext.isDev() || executorConfig.isEnableCluster()) {
            canConsumeTask = true;
            return;
        }

        //workerServer心跳线程启动
        WorkerServerThreadManager.getInstance().startWorkerServerThread();
    }

}
